from flask import Flask, render_template, request, jsonify
import paho.mqtt.client as mqtt
import threading

app = Flask(__name__)

# MQTT配置
MQTT_BROKER = "192.168.6.235"
MQTT_PORT = 1883
MQTT_TOPIC_to_RES = "test_topic_from_sat"
MQTT_TOPIC_to_SEND = "test_topic_from_grd"

# MQTT客户端
mqtt_client = mqtt.Client(callback_api_version=mqtt.CallbackAPIVersion.VERSION2)

# 全局变量用于保存收到的消息
received_messages = []

# MQTT收到消息的回调函数
def on_message(client, userdata, msg):
    global received_messages
    received_messages.append(msg.payload.decode())

# 连接MQTT代理并订阅主题
def connect_mqtt():
    mqtt_client.connect(MQTT_BROKER, MQTT_PORT, 60)
    mqtt_client.subscribe(MQTT_TOPIC_to_RES)
    mqtt_client.on_message = on_message
    mqtt_client.loop_forever()

# 启动MQTT连接和Flask服务器
mqtt_thread = threading.Thread(target=connect_mqtt)
mqtt_thread.start()

# Flask路由
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/messages')
def get_messages():
    global received_messages
    return jsonify(messages=received_messages)

@app.route('/send', methods=['POST'])
def send_message():
    message = request.form['message']
    mqtt_client.publish(MQTT_TOPIC_to_SEND, message)
    return '', 204

if __name__ == '__main__':
    app.run(debug=True)
